
import { Inject, Provide } from '@midwayjs/decorator';
import { JwtService } from '@midwayjs/jwt';
import { RespInfo, RespStatusCode } from '../types/common.type';
import { RespMethod } from '../util/common.method';

@Provide()
export class AuthService {
  @Inject()
  jwtService: JwtService;

  // async invoke() {
  // // 同步 API
  // this.jwtService.signSync(payload, secretOrPrivateKey, options);
  // this.jwtService.verifySync(token, secretOrPublicKey, options);
  // this.jwtService.decodeSync(token, options);

  // // 异步 API
  // await this.jwtService.sign(payload, secretOrPrivateKey, options);
  // await this.jwtService.verify(token, secretOrPublicKey, options);
  // await this.jwtService.decode(token, options);
  // }

  /** 生成 token */
  sign(uid: string): string {
    return this.jwtService.signSync({ uid });
  }
  /** 解密 token */
  decode(token: string): RespInfo {
    if (this.verify(token)) {
      const { uid } = this.jwtService.decodeSync(token) as any
      return RespMethod({ uid });
    } else {
      return RespMethod({}, RespStatusCode.Error, 'Token 无效');
    }
  }
  /** 检查 token 是否有效 */
  async verify(token: string): Promise<boolean> {
    try {
      const result = await this.jwtService.verify(token, {}) as any;
      return result?.exp > (Date.now() / 1000);
    } catch (error) {
      return false
    }
  }
}